
#include <iostream>
#include <string>
#include <sstream>
#include <sys/socket.h>
#include <sys/types.h>
#include <arpa/inet.h>
#include <netinet/in.h>
#include <vector>

#include "Log.hpp"
#include "Pthread.hpp"
#include "PthreadPool.hpp"

using namespace LogModule;
using namespace ThreadModlue;

int id;
int sockfd = 0;
std::string ip;
pthread_t port;

void Send()
{
    struct sockaddr_in server;
    server.sin_port = htons(port);
    server.sin_addr.s_addr = inet_addr(ip.c_str());
    server.sin_family = AF_INET;
    while(true)
    {
        std::string input;
        std::cout << "Plea Enter# ";
        std::getline(std::cin,input);

        sendto(sockfd,input.c_str(),input.size(),0,(struct sockaddr*)&server,sizeof(server));

        if(input == "QUIT")
        {
            pthread_cancel(id);
        }

    }
    
}

void Recv()
{
    while (true)
    {
        char buffer[1024];
        struct sockaddr_in peer;
        socklen_t len = sizeof(peer);
        int m = recvfrom(sockfd, buffer, sizeof(buffer) - 1, 0, (struct sockaddr *)&peer, &len);
        if (m > 0)
        {
            buffer[m] = 0;
            std::cerr << buffer << std::endl; // 2
        }
    }
}


// ./client ip port
int main(int argc,char* argv[])
{
    if(argc != 3)
    {
        LOG(LogLevel::ERROR) << "格式错误，正确格式为:  ./client ip port";
        return 1;
    }
    //拿到 ip + port
    ip = argv[1];
    port = atoi(argv[2]);

    Thread Sender(Send);
    Thread Recver(Recv);

    Sender.Start();
    Recver.Start();

    id = Recver.Id();

    Sender.Join();
    Recver.Join();

    return 0;
}